﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WXYW.DAL;
using WXYW.Entities;
using WXYW.Model;

namespace WXYW.BLL
{
    /// <summary>
    /// 对一些耗时较长的指标统计，采用后台预处理的方式
    /// </summary>
    public class ZBTJBackgroundService : RepositoryBase
    {
        public void CalculateSecondRepairZB()
        {
            int startYear = 2009;
            int endYear = DateTime.Now.Year;

            for (int year = startYear; year <= endYear; year++)
            {
                for (int month = 1; month <= 12; month++)
                {
                    string timePeriod = string.Format("{0}年{1}月", year, month);
                    string shortTimePeriod = string.Format("{0}月", month);
                    IQueryable<ZBTJData> zbtjDatas = GetEntities<ZBTJData>().Where(z => z.ZBTJType.Equals("二次维修率") && z.TimePeriod.Equals(timePeriod));
                    if (zbtjDatas.Count() > 0)
                    {
                        ZBTJData zbtjData = zbtjDatas.FirstOrDefault();
                        zbtjData.ZB = CalcilateSecondRepairZBOfMonth(year, month, year, month).ToString();
                        zbtjData.LastUpdateDate = DateTime.Now;
                        UpdateEntity(zbtjData);
                    }
                    else
                    {
                        ZBTJData zbtjData = new ZBTJData();
                        zbtjData.LastUpdateDate = DateTime.Now;
                        zbtjData.ShortTimePeriod = shortTimePeriod;
                        zbtjData.TimePeriod = timePeriod;
                        zbtjData.ZB = CalcilateSecondRepairZBOfMonth(year, month, year, month).ToString();
                        zbtjData.ZBTJType = "二次维修率";
                        InsertEntity(zbtjData);
                    }
                }
                CalcilateSecondRepairZBOfSeason(year, 1);
                CalcilateSecondRepairZBOfSeason(year, 2);
                CalcilateSecondRepairZBOfSeason(year, 3);
                CalcilateSecondRepairZBOfSeason(year, 4);
            }
        }

        public void CalcilateSecondRepairZBOfSeason(int year, int season)
        {
            string timePeriod = string.Format("{0}年Q{1}", year, season);
            string shortTimePeriod = string.Format("Q{0}", season);
            int startYear = year;
            int startMonth = 4;
            int endYear = year;
            int endMonth = 6;
            switch (season)
            { 
                case 1:
                    startYear = year;
                    endYear = year;
                    startMonth = 4;
                    endMonth = 6;
                    break;
                case 2:
                    startYear = year;
                    endYear = year;
                    startMonth = 7;
                    endMonth = 9;
                    break;
                case 3:
                    startYear = year;
                    endYear = year;
                    startMonth = 10;
                    endMonth = 12;
                    break;
                case 4:
                    startYear = year+1;
                    endYear = year+1;
                    startMonth = 1;
                    endMonth = 3;
                    break;
            }
            IQueryable<ZBTJData> zbtjDatas = GetEntities<ZBTJData>().Where(z => z.ZBTJType.Equals("二次维修率") && z.TimePeriod.Equals(timePeriod));
            if (zbtjDatas.Count() > 0)
            {
                ZBTJData zbtjData = zbtjDatas.FirstOrDefault();
                zbtjData.ZB = CalcilateSecondRepairZBOfMonth(startYear, startMonth, endYear, endMonth).ToString();
                zbtjData.LastUpdateDate = DateTime.Now;
                UpdateEntity(zbtjData);
            }
            else
            {
                ZBTJData zbtjData = new ZBTJData();
                zbtjData.LastUpdateDate = DateTime.Now;
                zbtjData.ShortTimePeriod = shortTimePeriod;
                zbtjData.TimePeriod = timePeriod;
                zbtjData.ZB = CalcilateSecondRepairZBOfMonth(startYear, startMonth, endYear, endMonth).ToString();
                zbtjData.ZBTJType = "二次维修率";
                InsertEntity(zbtjData);
            } 
        }

        public int CalcilateSecondRepairZBOfMonth(int startyear, int startmonth, int endyear, int endmonth)
        {
            DateTime startTime = DateTime.Now;
            if (startmonth > 1)
            {
                startTime = new DateTime(startyear, startmonth - 1, 25);
            }
            else
            {
                startTime = new DateTime(startyear - 1, 12, 25);
            }
            DateTime endTime = new DateTime(endyear, endmonth, 26);

            IQueryable<ApplicationProduct> products = GetEntities<ApplicationProduct>().Where(p => p.SendBackTime> startTime &&
                p.SendBackTime < endTime);
            int secondRepairCount = 0;
            foreach (ApplicationProduct product in products)
            {
                if (!product.ApplicationFormReference.IsLoaded)
                {
                    product.ApplicationFormReference.Load();
                }
                if (IsSecondRepair(product.ProductSerialNumber, product.SendBackTime.Value))
                {
                    secondRepairCount++;
                }
            }
            if (secondRepairCount > 0 && products.Count() >0)
            {
                return secondRepairCount * 100 / products.Count();
            }
            else
            {
                return 0;
            }
        }

        public bool IsSecondRepair(string serialNumber, DateTime lastestRepairTime)
        {
           bool isSecondRepair = false; 
           DateTime checkData = lastestRepairTime.AddMonths(-3);
           IQueryable<ApplicationProduct> products = GetEntities<ApplicationProduct>().Where(p => p.ProductSerialNumber.Equals(serialNumber) &&
               p.SendBackTime < lastestRepairTime &&
               p.SendBackTime > checkData);
           if (products.Count() > 0)
           {
               isSecondRepair = true;
           }              
           return isSecondRepair;
        }

        /// <summary>
        /// 供应商周期=收到工厂返回设备的日期-工厂收货的日期/当月台数（此为周期的平均周期）
        /// </summary>
        public void CalculateFactoryZQ()
        {
            int startYear = 2009;
            int endYear = DateTime.Now.Year;

            for (int year = startYear; year <= endYear; year++)
            {
                for (int month = 1; month <= 12; month++)
                {
                    string timePeriod = string.Format("{0}年{1}月", year, month);
                    string shortTimePeriod = string.Format("{0}月", month);
                    IQueryable<ZBTJData> zbtjDatas = GetEntities<ZBTJData>().Where(z => z.ZBTJType.Equals("供应商周期") && z.TimePeriod.Equals(timePeriod));
                    if (zbtjDatas.Count() > 0)
                    {
                        ZBTJData zbtjData = zbtjDatas.FirstOrDefault();
                        zbtjData.ZB = CalculateFactoryZQByMonth(year, month, year, month).ToString();
                        zbtjData.LastUpdateDate = DateTime.Now;
                        UpdateEntity(zbtjData);
                    }
                    else
                    {
                        ZBTJData zbtjData = new ZBTJData();
                        zbtjData.LastUpdateDate = DateTime.Now;
                        zbtjData.ShortTimePeriod = shortTimePeriod;
                        zbtjData.TimePeriod = timePeriod;
                        zbtjData.ZB = CalculateFactoryZQByMonth(year, month, year, month).ToString();
                        zbtjData.ZBTJType = "供应商周期";
                        InsertEntity(zbtjData);
                    }
                }
                CalculateFactoryZQBySeason(year, 1);
                CalculateFactoryZQBySeason(year, 2);
                CalculateFactoryZQBySeason(year, 3);
                CalculateFactoryZQBySeason(year, 4);
            }
        }

        public int CalculateFactoryZQByMonth(int startyear, int startmonth, int endyear, int endmonth)
        {
            DateTime startTime = DateTime.Now;
            if (startmonth > 1)
            {
                startTime = new DateTime(startyear, startmonth - 1, 25);
            }
            else
            {
                startTime = new DateTime(startyear - 1, 12, 25);
            }
            DateTime endTime = new DateTime(endyear, endmonth, 26);

            IQueryable<ReturnToFactoryForm> forms = GetEntities<ReturnToFactoryForm>(r => r.ApplyDate > startTime && r.ApplyDate < endTime &&
                r.FactoryReceiveDate.HasValue && r.ReceiveDate.HasValue);
            int totalZQ = 0;
            foreach (ReturnToFactoryForm form in forms)
            {
                totalZQ += DateTimeService.CalculateDateTimeSpan(form.FactoryReceiveDate.Value, form.ReceiveDate.Value);
            }
            int factoryZQ = 0;
            if (forms.Count() > 0)
            {
                factoryZQ = totalZQ / forms.Count();
            }
            return factoryZQ;
        }

        public void CalculateFactoryZQBySeason(int year, int season)
        {
            string timePeriod = string.Format("{0}年Q{1}", year, season);
            string shortTimePeriod = string.Format("Q{0}", season);
            int startYear = year;
            int startMonth = 4;
            int endYear = year;
            int endMonth = 6;
            switch (season)
            {
                case 1:
                    startYear = year;
                    endYear = year;
                    startMonth = 4;
                    endMonth = 6;
                    break;
                case 2:
                    startYear = year;
                    endYear = year;
                    startMonth = 7;
                    endMonth = 9;
                    break;
                case 3:
                    startYear = year;
                    endYear = year;
                    startMonth = 10;
                    endMonth = 12;
                    break;
                case 4:
                    startYear = year + 1;
                    endYear = year + 1;
                    startMonth = 1;
                    endMonth = 3;
                    break;
            }
            IQueryable<ZBTJData> zbtjDatas = GetEntities<ZBTJData>().Where(z => z.ZBTJType.Equals("供应商周期") && z.TimePeriod.Equals(timePeriod));
            if (zbtjDatas.Count() > 0)
            {
                ZBTJData zbtjData = zbtjDatas.FirstOrDefault();
                zbtjData.ZB = CalculateFactoryZQByMonth(startYear, startMonth, endYear, endMonth).ToString();
                zbtjData.LastUpdateDate = DateTime.Now;
                UpdateEntity(zbtjData);
            }
            else
            {
                ZBTJData zbtjData = new ZBTJData();
                zbtjData.LastUpdateDate = DateTime.Now;
                zbtjData.ShortTimePeriod = shortTimePeriod;
                zbtjData.TimePeriod = timePeriod;
                zbtjData.ZB = CalculateFactoryZQByMonth(startYear, startMonth, endYear, endMonth).ToString();
                zbtjData.ZBTJType = "供应商周期";
                InsertEntity(zbtjData);
            } 
        }

        /// <summary>
        /// 备件先行满足率=当天下5点之前申请并发货的数量/当天所有申请的总和*100%（下午5:00以后申请的计算到第2天的需求里面；同时此按照当天计算完成后按照月来输出结果）（上月26日至本月25日的）
        /// 包括 RMA DOA 和备件先行  不包括返厂
        /// </summary>
        public void CalculateBJXXStatisfyRate()
        {
            int startYear = 2009;
            int endYear = DateTime.Now.Year;
            for (int year = startYear; year <= endYear; year++)
            {
                int startMonth1 = 1;
                int endMonth1 = 12;
                string timePeriod;
                string shortTimePeriod;
                IQueryable<ZBTJData> zbtjDatas;
                for (int month = startMonth1; month <= endMonth1; month++)
                {
                    timePeriod = string.Format("{0}年{1}月", year, month);
                    shortTimePeriod = string.Format("{0}月", month);
                    zbtjDatas = GetEntities<ZBTJData>().Where(z => z.ZBTJType.Equals("备件先行满足率") && z.TimePeriod.Equals(timePeriod));
                    if (zbtjDatas.Count() > 0)
                    {
                        ZBTJData zbtjData = zbtjDatas.FirstOrDefault();
                        zbtjData.ZB = GetBJXXStatisfyRateOfMonth(year, month, year, month).ToString();
                        zbtjData.LastUpdateDate = DateTime.Now;
                        UpdateEntity(zbtjData);
                    }
                    else
                    {
                        ZBTJData zbtjData = new ZBTJData();
                        zbtjData.LastUpdateDate = DateTime.Now;
                        zbtjData.ShortTimePeriod = shortTimePeriod;
                        zbtjData.TimePeriod = timePeriod;
                        zbtjData.ZB = GetBJXXStatisfyRateOfMonth(year, month, year, month).ToString();
                        zbtjData.ZBTJType = "备件先行满足率";
                        InsertEntity(zbtjData);
                    } 
                }

                timePeriod = string.Format("{0}年Q{1}", year, 1);
                shortTimePeriod = string.Format("Q{0}", 1);

                zbtjDatas = GetEntities<ZBTJData>().Where(z => z.ZBTJType.Equals("备件先行满足率") && z.TimePeriod.Equals(timePeriod));
                if (zbtjDatas.Count() > 0)
                {
                    ZBTJData zbtjData = zbtjDatas.FirstOrDefault();
                    zbtjData.ZB = GetBJXXStatisfyRateOfMonth(year, 4, year, 6).ToString();
                    zbtjData.LastUpdateDate = DateTime.Now;
                    UpdateEntity(zbtjData);
                }
                else
                {
                    ZBTJData zbtjData = new ZBTJData();
                    zbtjData.LastUpdateDate = DateTime.Now;
                    zbtjData.ShortTimePeriod = shortTimePeriod;
                    zbtjData.TimePeriod = timePeriod;
                    zbtjData.ZB = GetBJXXStatisfyRateOfMonth(year, 4, year, 6).ToString();
                    zbtjData.ZBTJType = "备件先行满足率";
                    InsertEntity(zbtjData);
                }

                timePeriod = string.Format("{0}年Q{1}", year, 2);
                shortTimePeriod = string.Format("Q{0}", 2);

                zbtjDatas = GetEntities<ZBTJData>().Where(z => z.ZBTJType.Equals("备件先行满足率") && z.TimePeriod.Equals(timePeriod));
                if (zbtjDatas.Count() > 0)
                {
                    ZBTJData zbtjData = zbtjDatas.FirstOrDefault();
                    zbtjData.ZB = GetBJXXStatisfyRateOfMonth(year, 7, year, 9).ToString();
                    zbtjData.LastUpdateDate = DateTime.Now;
                    UpdateEntity(zbtjData);
                }
                else
                {
                    ZBTJData zbtjData = new ZBTJData();
                    zbtjData.LastUpdateDate = DateTime.Now;
                    zbtjData.ShortTimePeriod = shortTimePeriod;
                    zbtjData.TimePeriod = timePeriod;
                    zbtjData.ZB = GetBJXXStatisfyRateOfMonth(year, 7, year, 9).ToString();
                    zbtjData.ZBTJType = "备件先行满足率";
                    InsertEntity(zbtjData);
                }

                timePeriod = string.Format("{0}年Q{1}", year, 3);
                shortTimePeriod = string.Format("Q{0}", 3);

                zbtjDatas = GetEntities<ZBTJData>().Where(z => z.ZBTJType.Equals("备件先行满足率") && z.TimePeriod.Equals(timePeriod));
                if (zbtjDatas.Count() > 0)
                {
                    ZBTJData zbtjData = zbtjDatas.FirstOrDefault();
                    zbtjData.ZB = GetBJXXStatisfyRateOfMonth(year, 10, year, 12).ToString();
                    zbtjData.LastUpdateDate = DateTime.Now;
                    UpdateEntity(zbtjData);
                }
                else
                {
                    ZBTJData zbtjData = new ZBTJData();
                    zbtjData.LastUpdateDate = DateTime.Now;
                    zbtjData.ShortTimePeriod = shortTimePeriod;
                    zbtjData.TimePeriod = timePeriod;
                    zbtjData.ZB = GetBJXXStatisfyRateOfMonth(year, 10, year, 12).ToString();
                    zbtjData.ZBTJType = "备件先行满足率";
                    InsertEntity(zbtjData);
                }

                timePeriod = string.Format("{0}年Q{1}", year, 4);
                shortTimePeriod = string.Format("Q{0}", 4);

                zbtjDatas = GetEntities<ZBTJData>().Where(z => z.ZBTJType.Equals("备件先行满足率") && z.TimePeriod.Equals(timePeriod));
                if (zbtjDatas.Count() > 0)
                {
                    ZBTJData zbtjData = zbtjDatas.FirstOrDefault();
                    zbtjData.ZB = GetBJXXStatisfyRateOfMonth(year + 1, 1, year+1, 3).ToString();
                    zbtjData.LastUpdateDate = DateTime.Now;
                    UpdateEntity(zbtjData);
                }
                else
                {
                    ZBTJData zbtjData = new ZBTJData();
                    zbtjData.LastUpdateDate = DateTime.Now;
                    zbtjData.ShortTimePeriod = shortTimePeriod;
                    zbtjData.TimePeriod = timePeriod;
                    zbtjData.ZB = GetBJXXStatisfyRateOfMonth(year + 1, 1, year+1, 3).ToString();
                    zbtjData.ZBTJType = "备件先行满足率";
                    InsertEntity(zbtjData);
                }
            }
        }

        private int GetBJXXStatisfyRateOfMonth(int startYear, int startmonth, int endYear, int endMonth)
        {
            DateTime endDate = new DateTime(endYear, endMonth, 1, 17, 0, 0);
            endDate = endDate.AddMonths(1).AddDays(-1);

            DateTime startDate = new DateTime(startYear, startmonth, 1, 17, 0, 0).AddDays(-1);
            if (startDate.DayOfWeek == DayOfWeek.Monday)
            {
                startDate = startDate.AddDays(-2);
            }
            int bjxxTotalCount = GetEntities<ApplicationProduct>().Where(p => (p.ApplicationForm.ApplicationType.StartsWith("B") ||
                p.ApplicationForm.ApplicationType.Equals("R") || p.ApplicationForm.ApplicationType.Equals("D")) &&
                p.ApplicationForm.ApplicationDateTime > startDate && p.ApplicationForm.ApplicationDateTime < endDate).Count();
            //int bjTotalCount = GetEntities<SparePartApplyForm>().Where(s => s.ApplyTime > startDate && s.ApplyTime < endDate).Count();
            int totalCount = bjxxTotalCount;// + bjTotalCount;
            int totalStatisfyCount = 0;
            for (DateTime time = startDate; time <= endDate; time = time.AddDays(1))
            {
                totalStatisfyCount += GetBJXXStatisfyCount(time.Year, time.Month, time.Day);
            }

            if (totalCount > 0)
            {
                return totalStatisfyCount * 100 / totalCount;
            }
            return 0;
        }

        /// <summary>
        /// 1，备件先行 里面的已审批待发货里面操作发货 2，备件申请管理里面 操作审批
        /// </summary>
        /// <param name="year"></param>
        /// <param name="month"></param>
        /// <param name="day"></param>
        /// <returns></returns>
        public int GetBJXXStatisfyCount(int year, int month, int day)
        {
            DateTime endDate = new DateTime(year, month, day, 17, 0, 0);
            DateTime endDate1 = new DateTime(year, month, day, 23, 59, 59);
            DateTime startDate = endDate.AddDays(-1);
            if (endDate.DayOfWeek == DayOfWeek.Monday)
            {
                startDate = startDate.AddDays(-2);
            }
            // 备件先行满足条件的单数
            int bjxxStatisfyCount = GetEntities<ApplicationProduct>().Where(p =>
                //p.ApplicationForm.User.ServiceStation == null &&
                (p.ApplicationForm.ApplicationType.StartsWith("B") ||
                 p.ApplicationForm.ApplicationType.Equals("R") || 
                 p.ApplicationForm.ApplicationType.Equals("D"))&&
                p.ApplicationForm.ApplicationDateTime > startDate && 
                p.ApplicationForm.ApplicationDateTime < endDate &&
                p.ApplicationForm.SendBackDateTime < endDate1).Count();
            //int bjStatisfyCount = GetEntities<SparePartApplyForm>().Where(s => s.ApplyTime > startDate && s.ApplyTime < endDate &&
            //    s.DealWithTime < endDate1).Count();

            return bjxxStatisfyCount;
        }

        /// <summary>
        /// 备件清理率=5天从待修流程走的单量/当月所有派单的数量*100%
        /// 5天从待修流程走的单量 意思是从待修状态流转到其他流程状态的数
        /// 例如：待修里面有5台，我点击返厂2台 报价 1台 维修完毕2台 那就是 5/5
        /// 就是从派单开始计算5天处理了的
        /// </summary>
        /// <returns></returns>
        public int CalculateBJQLRate()
        {
            int startYear = 2009;
            int endYear = DateTime.Now.Year;
            string timePeriod;
            string shortTimePeriod;
            IQueryable<ZBTJData> zbtjDatas; 
            for (int year = startYear; year <= endYear; year++)
            {
                for (int month = 1; month <= 12; month++)
                {
                    timePeriod = string.Format("{0}年{1}月", year, month);
                    shortTimePeriod = string.Format("{0}月", month);
                    zbtjDatas = GetEntities<ZBTJData>().Where(z => z.ZBTJType.Equals("备件清理率") && z.TimePeriod.Equals(timePeriod));
                    if (zbtjDatas.Count() > 0)
                    {
                        ZBTJData zbtjData = zbtjDatas.FirstOrDefault();
                        zbtjData.ZB = CalculateBJQLRateOfMonthRange(year, month, year, month).ToString();
                        zbtjData.LastUpdateDate = DateTime.Now;
                        UpdateEntity(zbtjData);
                    }
                    else
                    {
                        ZBTJData zbtjData = new ZBTJData();
                        zbtjData.LastUpdateDate = DateTime.Now;
                        zbtjData.ShortTimePeriod = shortTimePeriod;
                        zbtjData.TimePeriod = timePeriod;
                        zbtjData.ZB = CalculateBJQLRateOfMonthRange(year, month, year, month).ToString();
                        zbtjData.ZBTJType = "备件清理率";
                        InsertEntity(zbtjData);
                    } 
                }

                timePeriod = string.Format("{0}年Q{1}", year, 1);
                shortTimePeriod = string.Format("Q{0}", 1);

                zbtjDatas = GetEntities<ZBTJData>().Where(z => z.ZBTJType.Equals("备件清理率") && z.TimePeriod.Equals(timePeriod));
                if (zbtjDatas.Count() > 0)
                {
                    ZBTJData zbtjData = zbtjDatas.FirstOrDefault();
                    zbtjData.ZB = CalcilateSecondRepairZBOfMonth(year, 4, year, 6).ToString();
                    zbtjData.LastUpdateDate = DateTime.Now;
                    UpdateEntity(zbtjData);
                }
                else
                {
                    ZBTJData zbtjData = new ZBTJData();
                    zbtjData.LastUpdateDate = DateTime.Now;
                    zbtjData.ShortTimePeriod = shortTimePeriod;
                    zbtjData.TimePeriod = timePeriod;
                    zbtjData.ZB = CalcilateSecondRepairZBOfMonth(year, 4, year, 6).ToString();
                    zbtjData.ZBTJType = "备件清理率";
                    InsertEntity(zbtjData);
                }

                timePeriod = string.Format("{0}年Q{1}", year, 2);
                shortTimePeriod = string.Format("Q{0}", 2);

                zbtjDatas = GetEntities<ZBTJData>().Where(z => z.ZBTJType.Equals("备件清理率") && z.TimePeriod.Equals(timePeriod));
                if (zbtjDatas.Count() > 0)
                {
                    ZBTJData zbtjData = zbtjDatas.FirstOrDefault();
                    zbtjData.ZB = CalcilateSecondRepairZBOfMonth(year, 7, year, 9).ToString();
                    zbtjData.LastUpdateDate = DateTime.Now;
                    UpdateEntity(zbtjData);
                }
                else
                {
                    ZBTJData zbtjData = new ZBTJData();
                    zbtjData.LastUpdateDate = DateTime.Now;
                    zbtjData.ShortTimePeriod = shortTimePeriod;
                    zbtjData.TimePeriod = timePeriod;
                    zbtjData.ZB = CalculateBJQLRateOfMonthRange(year, 7, year, 9).ToString();
                    zbtjData.ZBTJType = "备件清理率";
                    InsertEntity(zbtjData);
                }

                timePeriod = string.Format("{0}年Q{1}", year, 3);
                shortTimePeriod = string.Format("Q{0}", 3);

                zbtjDatas = GetEntities<ZBTJData>().Where(z => z.ZBTJType.Equals("备件清理率") && z.TimePeriod.Equals(timePeriod));
                if (zbtjDatas.Count() > 0)
                {
                    ZBTJData zbtjData = zbtjDatas.FirstOrDefault();
                    zbtjData.ZB = CalculateBJQLRateOfMonthRange(year, 10, year, 12).ToString();
                    zbtjData.LastUpdateDate = DateTime.Now;
                    UpdateEntity(zbtjData);
                }
                else
                {
                    ZBTJData zbtjData = new ZBTJData();
                    zbtjData.LastUpdateDate = DateTime.Now;
                    zbtjData.ShortTimePeriod = shortTimePeriod;
                    zbtjData.TimePeriod = timePeriod;
                    zbtjData.ZB = CalculateBJQLRateOfMonthRange(year, 10, year, 12).ToString();
                    zbtjData.ZBTJType = "备件清理率";
                    InsertEntity(zbtjData);
                }

                timePeriod = string.Format("{0}年Q{1}", year, 4);
                shortTimePeriod = string.Format("Q{0}", 4);

                zbtjDatas = GetEntities<ZBTJData>().Where(z => z.ZBTJType.Equals("备件清理率") && z.TimePeriod.Equals(timePeriod));
                if (zbtjDatas.Count() > 0)
                {
                    ZBTJData zbtjData = zbtjDatas.FirstOrDefault();
                    zbtjData.ZB = CalculateBJQLRateOfMonthRange(year + 1, 1, year+1, 3).ToString();
                    zbtjData.LastUpdateDate = DateTime.Now;
                    UpdateEntity(zbtjData);
                }
                else
                {
                    ZBTJData zbtjData = new ZBTJData();
                    zbtjData.LastUpdateDate = DateTime.Now;
                    zbtjData.ShortTimePeriod = shortTimePeriod;
                    zbtjData.TimePeriod = timePeriod;
                    zbtjData.ZB = CalculateBJQLRateOfMonthRange(year + 1, 1, year+1, 3).ToString();
                    zbtjData.ZBTJType = "备件清理率";
                    InsertEntity(zbtjData);
                }
            }
            return 0;
        }

        public int CalculateBJQLRateOfMonthRange(int startyear, int startmonth, int endyear, int endmonth)
        {
            int startMonth1 = startmonth;

            DateTime startDate = DateTime.Now;
            if (startMonth1 > 1)
            {
                startDate = new DateTime(startyear, startMonth1 - 1, 25);
            }
            else
            {
                startDate = new DateTime(startyear - 1, 12, 25);
            }
            DateTime endDate = new DateTime(endyear, endmonth, 26);
            
            IQueryable<ApplicationProduct> applicationProducts = GetEntities<ApplicationProduct>().Where(p=>
                p.DistributeDateTime > startDate && p.DistributeDateTime < endDate);
            int bjqlCount = 0;
            foreach (ApplicationProduct product in applicationProducts)
            {
                if (!product.ReturnToFactoryForm.IsLoaded)
                {
                    product.ReturnToFactoryForm.Load();
                }

                int dealWithDate1 = -1; // 返厂时间(返厂申请时间与派单时间之差)
                int dealWithDate2 = -1; // 升级时间
                int dealWithDate3 = -1; // 备件申请时间
                int dealWithDate4 = -1; // 维修时间
                int dealWithDate5 = -1; // 报价时间
                if (product.ReturnToFactoryForm.Count > 0)
                {
                    dealWithDate1 = DateTimeService.CalculateDateTimeSpan(
                         product.DistributeDateTime.Value,
                         product.ReturnToFactoryForm.FirstOrDefault().ApplyDate.Value);
                }

                if (!product.UpgradeForm.IsLoaded)
                {
                    product.UpgradeForm.Load();
                }
                if (product.UpgradeForm.Count > 0)
                {
                    dealWithDate2 = DateTimeService.CalculateDateTimeSpan(
                         product.DistributeDateTime.Value,
                         product.UpgradeForm.FirstOrDefault().ApplyTime.Value);
                }

                if (!product.SparePartApplyForm.IsLoaded)
                {
                    product.SparePartApplyForm.Load();
                }
                if (product.SparePartApplyForm.Count > 0)
                {
                    dealWithDate3 = DateTimeService.CalculateDateTimeSpan(
                         product.DistributeDateTime.Value,
                         product.SparePartApplyForm.FirstOrDefault().ApplyTime.Value);
                }

                if (product.RepairCompleteDateTime.HasValue)
                {
                    dealWithDate4 = DateTimeService.CalculateDateTimeSpan(
                             product.DistributeDateTime.Value,
                             product.RepairCompleteDateTime.Value);
                }

                if (product.QuotationDateTime.HasValue)
                {
                    dealWithDate5 = DateTimeService.CalculateDateTimeSpan(
                            product.DistributeDateTime.Value,
                            product.QuotationDateTime.Value);
                }

                if ((dealWithDate1 < 6 && dealWithDate1 > -1) ||
                    (dealWithDate2 < 6 && dealWithDate2 > -1) ||
                    (dealWithDate3 < 6 && dealWithDate3 > -1) ||
                    (dealWithDate4 < 6 && dealWithDate4 > -1) ||
                    (dealWithDate5 < 6 && dealWithDate5 > -1))
                {
                    bjqlCount++;
                }
            }
            if (applicationProducts.Count() > 0)
            {
                return bjqlCount*100 / applicationProducts.Count();
            }
            else
            {
                return 0;
            }
        }

        public int Calculate0To5Tat()
        {
            int to5TAT=0;
            ZBTJService service = new ZBTJService();
            int totalCount = service.GetTotalCompleteOfCurrentMonth(DateTime.Now.Year, DateTime.Now.Month);
            int sXCount = service.GetSXCountOfMonth(DateTime.Now.Year, DateTime.Now.Month, 5);
            if (totalCount > 0)
            {
                to5TAT = sXCount * 100 / totalCount;
            }
            ZBTJData zbtjData = new ZBTJData();
            zbtjData.LastUpdateDate = DateTime.Now;
            zbtjData.ShortTimePeriod = DateTime.Now.ToString("yyyy年MM月dd日");
            zbtjData.TimePeriod = DateTime.Now.ToString("yyyy年MM月dd日");
            zbtjData.ZB = to5TAT.ToString();
            zbtjData.ZBTJType = "0To5TAT";
            InsertEntity(zbtjData);
            return 0;
        }

        public int Calculate0To3Tat()
        {
            int to3TAT = 0;
            ZBTJService service = new ZBTJService();
            int totalCount = service.GetTotalBNCompleteCount(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Year, DateTime.Now.Month);
            int sXCount = service.GetS3Count(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Year, DateTime.Now.Month);
            if (totalCount > 0)
            {
                to3TAT = sXCount * 100 / totalCount;
            }
            ZBTJData zbtjData = new ZBTJData();
            zbtjData.LastUpdateDate = DateTime.Now;
            zbtjData.ShortTimePeriod = DateTime.Now.ToString("yyyy年MM月dd日");
            zbtjData.TimePeriod = DateTime.Now.ToString("yyyy年MM月dd日");
            zbtjData.ZB = to3TAT.ToString();
            zbtjData.ZBTJType = "0To3TAT";
            InsertEntity(zbtjData);
            return 0;
        }

        public int GetOTo5TAT()
        {
            ZBTJData zbtjData = GetEntities<ZBTJData>().Where(z => z.ZBTJType.Equals("0To5TAT")).OrderByDescending(z=>z.LastUpdateDate).FirstOrDefault();
            if (zbtjData != null)
            {
                return Convert.ToInt32(zbtjData.ZB);
            }
            return 0;
        }

        public int GetOTo3TAT()
        {
            ZBTJData zbtjData = GetEntities<ZBTJData>().Where(z => z.ZBTJType.Equals("0To3TAT")).OrderByDescending(z => z.LastUpdateDate).FirstOrDefault();
            if (zbtjData != null)
            {
                return Convert.ToInt32(zbtjData.ZB);
            }
            return 0;
        }
    }
}
